// // src/main.rs

// extern crate node_qrcode;
// use std::fs::File;
// use std::io::Write;

// use wasm_bindgen::{JsError, JsValue};

// fn main() -> Result<(), JsValue> {
//     let greeting = node_qrcode::generate_qr_code("World")?;
//     let buffer: &[u8] = &greeting;
//     // 打开或创建一个文件
//     let file = File::create("output.png");
//     match file {
//         Ok(mut file) => file.write_all(buffer).expect("fsa"),
//         Err(error) => {
//             return Err(JsValue::from_str(&format!(
//                 "Error generating QR code: {:?}",
//                 error
//             )))
//         }
//     };
//     Ok(())
// }

use qrcode::QrCode;
use image::{DynamicImage, ImageBuffer, Rgba, imageops};
use image::GenericImageView;
use std::path::Path;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 生成二维码
    let qr_code: QrCode = QrCode::with_error_correction_level("Hello, World发哈六点十分久啊发了撒旦法!", qrcode::EcLevel::H)?; // 使用高纠错级别
    let qr_image: ImageBuffer<Rgba<u8>, Vec<u8>> = qr_code.render::<Rgba<u8>>().min_dimensions(200, 200).build();

    // 读取中心图片
    let center_image_path: &Path = Path::new("avator.png");
    let center_image: ImageBuffer<Rgba<u8>, Vec<u8>> = image::open(center_image_path)?.to_rgba8();

    // 获取二维码和中心图片的尺寸
    let (qr_width, qr_height) = qr_image.dimensions();
    let (center_width, center_height) = center_image.dimensions();

    // 确保中心图片的尺寸不超过二维码的 20%
    let max_size = (qr_width.min(qr_height) as f32 * 0.2) as u32;
    let scale_factor = max_size as f32 / center_width.max(center_height) as f32;
    let resized_center_width = (center_width as f32 * scale_factor) as u32;
    let resized_center_height = (center_height as f32 * scale_factor) as u32;

    // 缩放中心图片
    let resized_center_image = imageops::resize(&center_image, resized_center_width, resized_center_height, imageops::FilterType::Nearest);

    // 创建一个新的图像缓冲区
    let mut final_image = ImageBuffer::new(qr_width, qr_height);

    // 将二维码复制到新的图像缓冲区
    for (x, y, pixel) in qr_image.enumerate_pixels() {
        final_image.put_pixel(x, y, *pixel);
    }

    // 计算中心图片的位置
    let x_offset = (qr_width - resized_center_width) / 2;
    let y_offset = (qr_height - resized_center_height) / 2;

    // 将中心图片复制到新的图像缓冲区
    for (x, y, pixel) in resized_center_image.enumerate_pixels() {
        final_image.put_pixel(x + x_offset, y + y_offset, *pixel);
    }

    // 保存最终的图像
    final_image.save("final_qr_code.png")?;

    println!("二维码生成成功！");
    Ok(())
}